<template>
  <div class="course-reviews-container">
    <div class="header">
      <div class="course-info">
        <el-button :icon="Back" @click="$router.push('/back/courses')" size="small">返回</el-button>
        <h2>{{ course.title }} - 课程评价</h2>
      </div>
      <div class="stats">
        <div class="stat-item">
          <span class="label">总评分</span>
          <span class="value">
            <el-rate
              v-model="averageRating"
              disabled
              show-score
              text-color="#ff9900"
            />
          </span>
        </div>
        <div class="stat-item">
          <span class="label">评价数</span>
          <span class="value">{{ total }}</span>
        </div>
      </div>
    </div>

    <el-empty v-if="total === 0" description="暂无评价" />

    <div v-else class="reviews-list">
      <el-card v-for="review in reviewList" :key="review.id" class="review-card">
        <template #header>
          <div class="review-header">
            <div class="user-info">
              <el-avatar :size="32" :src="review.avatar">{{ review.username?.charAt(0) }}</el-avatar>
              <span class="username">{{ review.username }}</span>
            </div>
            <div class="rating">
              <el-rate
                v-model="review.rating"
                disabled
                text-color="#ff9900"
              />
              <span class="date">{{ formatDate(review.createdTime) }}</span>
            </div>
          </div>
        </template>
        <div class="review-content">
          {{ review.content || '该用户未填写评价内容' }}
        </div>
        <div class="review-actions" v-if="userStore.isAdmin">
          <el-button type="danger" size="small" @click="handleDelete(review)" :icon="Delete">删除</el-button>
        </div>
      </el-card>

      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @update:current-page="currentPage = $event"
        @update:page-size="pageSize = $event"
        class="pagination"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { Back, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 课程ID
const courseId = computed(() => route.params.id)

// 状态变量
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const reviewList = ref([])
const course = ref({})
const averageRating = ref(0)

// 获取课程信息
const fetchCourse = async () => {
  try {
    await request.get(`/course/${courseId.value}`, null, {
      showDefaultMsg: false,
      onSuccess: (res) => {
        course.value = res
      }
    })
  } catch (error) {
    console.error('获取课程信息失败:', error)
    ElMessage.error('获取课程信息失败')
    router.push('/back/courses')
  }
}

// 获取评价列表
const fetchReviews = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    await request.get(`/review/course/${courseId.value}`, params, {
      showDefaultMsg: false,
      onSuccess: (res) => {
        reviewList.value = res.records||[]
        total.value = res.total||0
        
        // 计算平均评分
        if (res.records.length > 0) {
          const totalRating = res.records.reduce((sum, review) => sum + review.rating, 0)
          averageRating.value = totalRating / res.records.length
        }
      }
    })
  } catch (error) {
    console.error('获取评价列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchReviews()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchReviews()
}

// 处理删除评价
const handleDelete = (review) => {
  ElMessageBox.confirm(
    '确定要删除该评价吗？此操作不可恢复。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await request.delete(`/review/${review.id}`, {
        successMsg: '删除成功'
      })
      fetchReviews()
    } catch (error) {
      console.error('删除评价失败:', error)
    }
  })
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '暂无'
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

// 初始化
onMounted(() => {
  fetchCourse()
  fetchReviews()
})
</script>

<style lang="scss" scoped>
.course-reviews-container {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    flex-wrap: wrap;
    gap: 20px;

    .course-info {
      display: flex;
      align-items: center;
      gap: 10px;

      h2 {
        margin: 0;
        font-size: 22px;
        color: var(--el-text-color-primary);
      }
    }

    .stats {
      display: flex;
      gap: 30px;

      .stat-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .label {
          font-size: 14px;
          color: var(--el-text-color-secondary);
          margin-bottom: 5px;
        }
        
        .value {
          font-size: 18px;
          font-weight: 600;
          color: var(--el-color-primary);
        }
      }
    }
  }

  .reviews-list {
    margin-top: 20px;
    
    .review-card {
      margin-bottom: 20px;
      
      .review-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .user-info {
          display: flex;
          align-items: center;
          gap: 10px;
          
          .username {
            font-weight: 600;
          }
        }
        
        .rating {
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          
          .date {
            font-size: 12px;
            color: var(--el-text-color-secondary);
            margin-top: 5px;
          }
        }
      }
      
      .review-content {
        margin: 15px 0;
        font-size: 14px;
        line-height: 1.6;
        color: var(--el-text-color-primary);
      }
      
      .review-actions {
        display: flex;
        justify-content: flex-end;
        margin-top: 10px;
      }
    }
    
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
}
</style> 